package homework.four;

import com.sun.java_cup.internal.runtime.Symbol;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

public class ColumnInfo {
    private String columnName;          // 字段名
    private Class<?> type;              // 字段类型
    private boolean isID = false;       // 是否为主键
    private boolean nullable = true;    // 是否为空
    private int length = 32;            // 字段长度
    private boolean needPersist = false;// 字段是否需要保存到数据库中

    public ColumnInfo parse(Field filed){
        this.columnName = filed.getName();
        this.type = filed.getType();
        Annotation[] annotations = filed.getAnnotations();
        for(Annotation annotation : annotations){
            if(annotation.annotationType().equals(Column.class)){
                                        // 如果注解是@Column
                this.needPersist = true;// 设置成需要持久化存储
                Column column = (Column)annotation;
                if(!column.value().equals("")){// 若value不为空，设置字段名
                    this.columnName = column.value();
                }

                this.nullable = column.nullable();
                if(column.length() != -1){// 若length不为空，设置字段长度
                    this.length = column.length();
                }else if(annotation.annotationType().equals(ID.class)){
                    this.needPersist = true;
                    ID id = (ID)annotation;
                    this.isID = true;
                    if(!id.value().equals("")){// 以value值作为字段名
                        this.columnName = id.value();
                    }
                }
            }
        }
        if(this.needPersist){
            return this;
        }else{
            return null;
        }
    }

    @Override
    public String toString(){
        StringBuilder sql = new StringBuilder(columnName);
        if(this.type.equals(String.class)){
            sql.append(Constant.BLANK + "varchar(" + this.length + ")");
        }else if(this.type.equals(Integer.class)){
            sql.append(Constant.BLANK + "int");
        }
        if(this.isID){
            sql.append(Constant.BLANK + "primary key");
        }
        if(!this.nullable){
            sql.append(Constant.BLANK + "not null");
        }
        if(this.nullable){
            sql.append(Constant.BLANK + "null");
        }
        sql.append(";");
        return sql.toString();
    }
}
